//
//  WNDiscoverVC.swift
//  WalkNovel
//
//  Created by Kevin on 2023/11/6.
//

import UIKit

let TopHeader = "DiscTopReusableView"

class WNDiscoverVC: WNBaseVC {
    
    lazy var searchView: WNSearchView = {
        let view = WNSearchView()
        view.searchType(0)
        return view
    }()
    
    lazy var disColView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .vertical
        let col = UICollectionView.init(frame: .zero, collectionViewLayout: layout)
        col.showsVerticalScrollIndicator = false
        col.showsHorizontalScrollIndicator = false
        col.backgroundColor = .white
        col.delegate = self
        col.dataSource = self
        col.register(DisAllBannerColCell.self, forCellWithReuseIdentifier: DisAllBannerColCell.identifier)
        col.register(DisTypePopColCell.self, forCellWithReuseIdentifier: DisTypePopColCell.identifier)
        col.register(DisTypeGreatColCell.self, forCellWithReuseIdentifier: DisTypeGreatColCell.identifier)
        col.register(DisTypeUpdateColCell.self, forCellWithReuseIdentifier: DisTypeUpdateColCell.identifier)
        col.register(RecColCell.self, forCellWithReuseIdentifier: RecColCell.identifier)
        col.register(DiscTopReusableView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: TopHeader)
        col.ly_emptyView = WNEmptyView.wn_loadStyle(descStr: .discover, imageStr: .discover, tapBlock: { [weak self] in
            self?.getDisRequest()
        })
        col.isHidden = true
        return col
    }()
    
    var categoryBookArr = [CategoryBookModel]()
    
    var recArr = [BookDetailModel]()
    
    var hasLoad = false
    
    var lastPBCount = 0
    
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        dataRequest()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    override func viewConfig() {
        wn_hidNavView()
        view.addSubview(searchView)
        view.addSubview(disColView)
        searchView.snp.makeConstraints { (make) in
            make.top.equalTo(StatusBarHeight)
            make.left.right.equalTo(0)
            make.height.equalTo(44)
        }
        disColView.snp.makeConstraints { (make) in
            make.top.equalTo(searchView.snp.bottom).offset(0)
            make.left.right.equalTo(0)
            make.bottom.equalTo(-TabBarTotalHeight)
        }
    }
    
    override func dataConfig() {
        pageName = "Discover"
        listSettingRefresh()
        getDisRequest()
        getRecRequest()
        disColView.mj_header = wn_refreshHeader(completion: { [weak self] in
            self?.getDisRequest()
        })
        WNThread.wn_delay(2) {
            self.handlePasteboardStr()
        }
    }
    
    override func handleNoti() {
        NotificationCenter.default.addObserver(forName: WNNotiName.loginNoti, object: nil, queue: nil) { [weak self] not in
            self?.getDisRequest()
        }
        NotificationCenter.default.addObserver(self, selector: #selector(becomeActiveNoti), name: UIApplication.didBecomeActiveNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(enterBackgroundNoti), name: UIApplication.didEnterBackgroundNotification, object: nil)
    }
}

extension WNDiscoverVC: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        guard categoryBookArr.count > 0 else {
            return 0
        }
        let catC = (categoryBookArr.count > 4 ? 4 : categoryBookArr.count)
        let recC = recArr.count > 0 ? 1 : 0
        return catC + recC
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        switch section {
        case 0, 1, 2:
            return 1
        case 3:
            if categoryBookArr.count > 3 {
                let count = categoryBookArr[section].bookList?.count ?? 0
                return count > 6 ? 6 : count
            }else {
                return 0
            }
        case 4:
            return recArr.count
        default:
            return 0
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        switch indexPath.section {
        case 0:
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: DisAllBannerColCell.identifier, for: indexPath) as! DisAllBannerColCell
            if categoryBookArr.count > 0 {
                cell.bannerArr = categoryBookArr[0].bookList
            }
            cell.isHidden = categoryBookArr.count < 1
            return cell
        case 1:
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: DisTypePopColCell.identifier, for: indexPath) as! DisTypePopColCell
            if categoryBookArr.count > 1 {
                cell.popArr = categoryBookArr[1].bookList
            }
            cell.isHidden = categoryBookArr.count < 2
            return cell
        case 2:
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: DisTypeGreatColCell.identifier, for: indexPath) as! DisTypeGreatColCell
            if categoryBookArr.count > 2 {
                cell.greatArr = categoryBookArr[2].bookList
            }
            cell.isHidden = categoryBookArr.count < 3
            return cell
        case 3:
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: DisTypeUpdateColCell.identifier, for: indexPath) as! DisTypeUpdateColCell
            if categoryBookArr.count > 3 {
                cell.model = categoryBookArr[3].bookList?[indexPath.item]
            }
            cell.isHidden = categoryBookArr.count < 4
            return cell
        default:
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: RecColCell.identifier, for: indexPath) as! RecColCell
            cell.model = recArr[indexPath.item]
            return cell
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        switch indexPath.section {
        case 3:
            if categoryBookArr.count > 3 {
                wn_pushBookVC(categoryBookArr[3].bookList?[indexPath.item].bookId ?? "")
            }
        case 4:
            wn_pushBookVC(recArr[indexPath.item].bookId ?? "")
        default:
            return
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        if kind == UICollectionView.elementKindSectionHeader {
            let topView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: TopHeader, for: indexPath) as? DiscTopReusableView
            switch indexPath.section {
            case 1, 2, 3:
                if categoryBookArr.count > indexPath.section {
                    topView?.viewBtn.isHidden = false
                    let category = categoryBookArr[indexPath.section].category
                    topView?.leftLabel.text = category
                    topView?.categoryClosure = { [weak self] in
                        self?.wn_pushTypeBookVC(TagsModel(id: category, label_name: category), false)
                    }
                    topView?.isHidden = false
                }else {
                    topView?.isHidden = true
                }
            case 4:
                topView?.viewBtn.isHidden = true
                topView?.leftLabel.text = "Recommend"
            default:
                return UICollectionReusableView()
            }
            return topView!
        }
        return UICollectionReusableView()
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        switch indexPath.section {
        case 0:
            return CGSize(width: ScreenW, height: categoryBookArr.count < 1 ? 0.0 : scaleWidth(155)+24)
        case 1:
            return CGSize(width: ScreenW, height:  categoryBookArr.count < 2 ? 0.0 : scaleWidth(116)+24+16)
        case 2:
            return CGSize(width: ScreenW, height:  categoryBookArr.count < 3 ? 0.0 : scaleWidth(140)+12+12+108+16)
        case 3:
            return CGSize(width: scaleWidth(100), height:  categoryBookArr.count < 4 ? 0.0 : scaleWidth(144)+60)
        case 4:
            return CGSize(width: (ScreenW-36)*0.5, height: recArr[indexPath.item].recH)
        default:
            return .zero
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        return section == 0 ? .zero : .init(width: ScreenW, height: 40)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return section == 4 ? 8 : 0
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        switch section {
        case 3:
            return (ScreenW-scaleWidth(100)*3-25)*0.5
        case 4:
            return 8
        default:
            return 0
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        switch section {
        case 3:
            return .init(top: 12, left: 12, bottom: 0, right: 12)
        case 4:
            return .init(top: 8, left: 14, bottom: 8, right: 14)
        default:
            return .zero
        }
    }
}

extension WNDiscoverVC {
    
    func listSettingRefresh() {
        disColView.mj_header = wn_refreshHeader(completion: { [weak self] in
            self?.page = 1
            self?.hasPage = false
            self?.getDisRequest()
        })
        
        disColView.mj_footer = wn_refreshFooter(completion: { [weak self] in
            if self?.page == 1 && (self?.recArr.count ?? 0) == 0 {
                self?.disColView.mj_footer?.endRefreshing()
                return
            }
            if self?.hasPage == true {
                self?.page += 1
                self?.getRecRequest()
            }else {
                self?.disColView.mj_footer?.endRefreshingWithNoMoreData()
            }
        })
    }
}

extension WNDiscoverVC {
    
    func dataRequest() {
        let group = DispatchGroup()
        group.enter()
        provider_user.rx.request(.checkTicket)
            .asObservable().mapModel(BaseModel<[TicketModel]>.self)
            .subscribe(onNext: { (model) in
                guard model.code == 0 else { return group.leave() }
                saveHasCheck(true)
                if let arr = model.data, arr.filter({$0.status == 2}).count > 0 {
                    saveHasCheck(false)
                }
                group.leave()
            }, onError: { (error) in
                group.leave()
            }).disposed(by: rx.disposeBag)
        group.enter()
        provider_login.rx.request(.checkUser)
            .asObservable().mapModel(BaseModel<UserDetailModel>.self)
            .subscribe(onNext: { (model) in
                guard model.code == 0 else { return group.leave() }
                if let data = model.data {
                    saveUser(user: data)
                    setKeyUserId(data.userId ?? "")
                    WNSingleData.shared.userGold = data.gold
                }
                group.leave()
            }, onError: { (error) in
                group.leave()
            }).disposed(by: rx.disposeBag)
        group.notify(queue: DispatchQueue.main) { [weak self] in
            self?.searchView.readImage.isHidden = getHasCheck()
        }
    }
    
    func getDisRequest() {
        provider_discover.rx.request(.discover("FOR U"))
            .asObservable().mapModel(BaseModel<DiscoverModel>.self)
            .subscribe(onNext: { [weak self] (model) in
                guard model.code == 0 else {
                    return
                }
                if let m = model.data?.categoryList, m.count > 0 {
                    self?.categoryBookArr = m
                    if (self?.categoryBookArr.count ?? 0) > 1 {
                        self?.categoryBookArr.swapAt(0, 1)
                    }
                    if getFirstLand() {
                        saveFirstLand(false)
                        WNBuriedManager.shared.startEvents("open")
                        WNBuriedManager.shared.startEvents("start")
                        WNBuriedManager.shared.startEvents("home page")
                    }
                    self?.getRecRequest()
                }
            }, onError: { (error) in
            }).disposed(by: rx.disposeBag)
    }
    
    func getRecRequest() {
        WNHUD.wn_showLoading()
        provider_recommend.rx.request(.recommend(page))
            .asObservable().mapModel(BaseModel<[BookDetailModel]>.self)
            .subscribe(onNext: { [weak self] (model) in
                WNHUD.wn_hide()
                self?.disColView.isHidden = false
                self?.disColView.ly_emptyView.imageStr = EmptyImage.discover.rawValue
                self?.disColView.ly_emptyView.detailStr = EmptyDesc.discover.rawValue
                self?.disColView.ly_emptyView.btnTitleStr = ""
                guard model.code == 0 else {
                    if (self?.isFirst ?? true) {
                        self?.disColView.ly_emptyView.imageStr = EmptyImage.serverBad.rawValue
                        self?.disColView.ly_emptyView.detailStr = EmptyDesc.serverBad.rawValue
                        self?.disColView.ly_emptyView.btnTitleStr = "Click Refresh"
                    }else {
                        self?.wn_toast(model.msg ?? "")
                    }
                    self?.disColView.mj_header?.endRefreshing()
                    self?.disColView.mj_footer?.endRefreshing()
                    self?.isFirst = false
                    return
                }
                if self?.page == 1 {
                    self?.recArr.removeAll()
                    self?.disColView.mj_footer?.resetNoMoreData()
                }
                if let arr = model.data {
                    self?.hasPage = arr.count > 17
                    self?.recArr += arr
                }else {
                    self?.disColView.mj_footer?.endRefreshingWithNoMoreData()
                }
                self?.disColView.reloadData()
                self?.disColView.mj_header?.endRefreshing()
                self?.disColView.mj_footer?.endRefreshing()
                self?.isFirst = false
            }, onError: { [weak self] (error) in
                self?.wn_toast("Check the network connection")
                self?.disColView.ly_emptyView.imageStr = EmptyImage.netWork.rawValue
                self?.disColView.ly_emptyView.detailStr = EmptyDesc.netWork.rawValue
                self?.disColView.ly_emptyView.btnTitleStr = "Click Refresh"
                self?.disColView.mj_header?.endRefreshing()
                self?.disColView.mj_footer?.endRefreshing()
                self?.disColView.isHidden = false
            }).disposed(by: rx.disposeBag)
    }
    
//    func pasteboardRequest(_ str: String, completion: @escaping (BookDetailModel?) -> Void) {
//        provider_login.rx.request(.pasteboard(str))
//            .asObservable().mapModel(BaseModel<BookDetailModel>.self)
//            .subscribe(onNext: { (model) in
//                guard model.code == 0 else {
//                    completion(nil)
//                    return
//                }
//                if let m = model.data {
//                    completion(m)
//                }else {
//                    completion(nil)
//                }
//            }, onError: { (error) in
//                completion(nil)
//            }).disposed(by: rx.disposeBag)
//    }
    
    func attributionRequest(_ attId: String = "") {
        let userId = getUser()?.userId ?? ""
        guard attId.count > 0 else { return }
        provider_login.rx.request(.attribution(attId, userId))
            .asObservable().mapModel(BaseModel<String>.self)
            .subscribe(onNext: { [weak self] (model) in
                guard model.code == 0 else {
                    return
                }
                saveADTIME(NSDate().timeIntervalSince1970)
                self?.wn_pushBookVC(getADBOOKID(), "-100")
            }, onError: { (error) in
            }).disposed(by: rx.disposeBag)
    }
}

extension WNDiscoverVC {
    @objc func becomeActiveNoti() {
        clearPushInfo()
        if hasLoad {
            guard isLogin() else { return }
            if let vc = wn_getTopVC(), vc.isKind(of: WNDiscoverVC.self) {
                handlePasteboardStr()
                hasLoad = false
            }
        }
    }
    
    @objc func enterBackgroundNoti() {
        hasLoad = true
    }
    
    func clearPushInfo() {
        let nowTime = NSDate().timeIntervalSince1970
        let adTime = getADTIME()
        let adBook = getADBOOKID()
        if adBook.count > 0 {
            let offset = (nowTime - adTime) / 60.0
            if offset > 10 {
                saveADBOOKID("")
            }
        }
    }
    
    func handlePasteboardStr() {
        guard isLogin() else { return }
        let count = UIPasteboard.general.changeCount
        guard count != lastPBCount else { return }
        lastPBCount = count
        let str = checkPBStr()
        if str.count > 0 {
            UIPasteboard.general.string = nil
            attributionRequest(str)
        }
    }
    
    func checkPBStr() -> String {
        guard UIPasteboard.general.hasStrings else { return "" }
        guard let str = UIPasteboard.general.string else { return "" }
        guard str.count > 0 else { return "" }
        let key = "webnovel"
        var adid = ""
        var lanuage = "zh_TW"
        if str.contains(key) {
            let arr = str.components(separatedBy: "-")
            if arr.count > 1 {
                adid = arr[1]
                if adid.count > 0 {
                    saveADID(adid)
                }
            }
            if arr.count > 2 {
                let bookId = arr[2]
                if bookId.count > 0 {
                    saveADBOOKID(bookId)
                }
            }
            if arr.count > 3 {
               lanuage = arr[3]
            }
        }
        return adid
    }
}
